#include "healthCheck.h"

static void Health_start(void);
static void Health_finish(void);

HealthClassStruct HealthClass = {
    .init = Health_init,
    .startCheck = Health_start,
    .finishCheck = Health_finish,
};


#define UARTx       UART_NUM_2
#define TXD_PIN     GPIO_NUM_17
#define RXD_PIN     GPIO_NUM_16

static const int RX_BUF_SIZE = 76;
static char* TAG = "HealthCheck";


static void Health_run_task(void *pvParameters)
{
    uint8_t* data = (uint8_t*) malloc(RX_BUF_SIZE+1);
    while(1) 
    {
        const int rxBytes = uart_read_bytes(UARTx, data, RX_BUF_SIZE, 1000 / portTICK_PERIOD_MS);
        if(rxBytes > 0) 
        {
            data[rxBytes] = 0;
            if((data[0] == 0xFF) && (data[75] != 0))
            {
                memcpy(&HealthClass.HealthData, data, sizeof(HealthDataStruct));
            }
            printf("HEALTH: xinlv: %d, xueyang: %d, weixunhuan: %d, shousuoya: %d, shuzhangya: %d\n", HealthClass.HealthData.heartRate, HealthClass.HealthData.spo, HealthClass.HealthData.bk, HealthClass.HealthData.rsv[3], HealthClass.HealthData.rsv[4]);
        }
    }
    free(data);
}
static void Health_start(void)
{
    uint8_t cmd = 0x8A;
    uart_write_bytes(UARTx, &cmd, 1);
    ESP_LOGI(TAG, "health check started");
}

static void Health_finish(void)
{
    uint8_t cmd = 0x88;
    uart_write_bytes(UARTx, &cmd, 1);
    ESP_LOGI(TAG, "health check finished");
}

void Health_init(void) 
{
    const uart_config_t uart_config = {
        .baud_rate = 38400,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_APB,
    };
    // We won't use a buffer for sending data.
    uart_driver_install(UARTx, RX_BUF_SIZE * 2, 0, 0, NULL, 0);
    uart_param_config(UARTx, &uart_config);
    uart_set_pin(UARTx, TXD_PIN, RXD_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    ESP_LOGI(TAG, "health check init complate");

    xTaskCreate(Health_run_task, "Health_run_task", 2048, NULL, 0, NULL);
}